package com.softstao.guoyu.ui.activity.me;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.GsonManager;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.global.UserManager;
import com.softstao.guoyu.model.me.AuditApplyCondition;
import com.softstao.guoyu.model.me.AuditDetail;
import com.softstao.guoyu.model.me.Level;
import com.softstao.guoyu.model.me.User;
import com.softstao.guoyu.mvp.interactor.UploadInteractor;
import com.softstao.guoyu.mvp.interactor.agent.AgentInteractor;
import com.softstao.guoyu.mvp.interactor.me.AuditInteractor;
import com.softstao.guoyu.mvp.presenter.UploadPresenter;
import com.softstao.guoyu.mvp.presenter.agent.AgentPresenter;
import com.softstao.guoyu.mvp.presenter.me.AuditPresenter;
import com.softstao.guoyu.mvp.viewer.UploadTargetViewer;
import com.softstao.guoyu.mvp.viewer.agent.AuditViewer;
import com.softstao.guoyu.mvp.viewer.me.AuditAddViewer;
import com.softstao.guoyu.ui.baseAdapter.CommonBaseAdapter;
import com.softstao.guoyu.ui.baseAdapter.ViewHolder;
import com.softstao.softstaolibrary.library.activity.ImagePagerActivity;
import com.softstao.softstaolibrary.library.widget.CustomGridView;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.softstao.softstaolibrary.library.widget.progressBar.RoundProgressBarWidthNumber;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/23.
 */

public class AuditAddActivity extends BaseActivity implements AuditAddViewer, UploadTargetViewer, AuditViewer {

    @AIPresenter(presenter = AuditPresenter.class, interactor = AuditInteractor.class)
    AuditPresenter presenter;
    @AIPresenter(presenter = UploadPresenter.class, interactor = UploadInteractor.class)
    UploadPresenter uploadPresenter;
    @AIPresenter(presenter = AgentPresenter.class, interactor = AgentInteractor.class)
    AgentPresenter agentPresenter;

    @BindView(R.id.user_id)
    TextView userId;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.mobile)
    TextView mobile;
    @BindView(R.id.wechat)
    TextView wechat;
    @BindView(R.id.current_level)
    TextView currentLevel;
    @BindView(R.id.parent_name)
    TextView parentName;
    @BindView(R.id.apply_time)
    TextView applyTime;
    @BindView(R.id.apply_reason)
    EditText applyReason;
    @BindView(R.id.bond)
    TextView bond;
    @BindView(R.id.pay_img_view)
    CustomGridView payImgView;
    @BindView(R.id.level_name)
    TextView levelName;
    @BindView(R.id.memo)
    TextView memo;
    @BindView(R.id.scroll_view)
    CustomScrollerView scrollView;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.progress_layout)
    RelativeLayout progressLayout;
    @BindView(R.id.progress)
    RoundProgressBarWidthNumber progress;
    @BindView(R.id.pay_img)
    LinearLayout payImg;
    private User user;
    private Level level;
    private AuditApplyCondition condition = new AuditApplyCondition();
    private String level_name = "";
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private CommonBaseAdapter<String> imgAdapter;
    private List<String> datas = new ArrayList<>();
    private AuditDetail auditDetail;
    private int id;
    public final static int IMAGE = 100;

    @Override
    public int _ContentView() {
        return R.layout.activity_audit_add;
    }

    @Override
    public void initView() {
        level = (Level) getIntent().getSerializableExtra("level");
        initTitle(level.getName().substring(0, 2) + "授权申请");
        levelName.setText(level.getName());
        memo.setText(level.getMemo());
        bond.setText(level.getBond());
        id = getIntent().getIntExtra("id", 0);
        auditDetail = (AuditDetail) getIntent().getSerializableExtra("detail");
        if (level.getId()==1||level.getId()==2){
            payImg.setVisibility(View.GONE);
        }

        if (auditDetail == null) {
            user = UserManager.getInstance().getUser();
            userId.setText(SharePreferenceManager.getInstance().getAgentId()+"");
            name.setText(user.getName());
            mobile.setText(user.getMobile());
            wechat.setText(user.getWechat());
            switch (User.Type.fromInteger(user.getLevel())) {
                case ANGEL:
                    level_name = "天使";
                    break;
                case CROWN:
                    level_name = "皇冠";
                    break;
                case ONE_LEVEL:
                    level_name = "一级";
                    break;
                case CITY_LEVEL:
                    level_name = "市级";
                    break;
                case PROVINCE:
                    level_name = "省代";
                    break;
                case HEADQUARTER:
                    level_name = "总部";
                    break;
                case UNAGENT:
                    level_name = "未授权";
                    break;
            }
            currentLevel.setText(level_name);
            parentName.setText(user.getParentName());
            applyTime.setText(format.format(new Date(System.currentTimeMillis())));
        } else {
            userId.setText(auditDetail.getSubAuditInfo().getSubAgentId() + "");
            name.setText(auditDetail.getSubAuditInfo().getSubAgentname());
            mobile.setText(auditDetail.getSubAuditInfo().getSubAgentMobile());
            wechat.setText(auditDetail.getSubAuditInfo().getSubAgentWechat());
            switch (User.Type.fromInteger(auditDetail.getSubAuditInfo().getSubAgentLevel())) {
                case ANGEL:
                    level_name = "天使";
                    break;
                case CROWN:
                    level_name = "皇冠";
                    break;
                case ONE_LEVEL:
                    level_name = "一级";
                    break;
                case CITY_LEVEL:
                    level_name = "市级";
                    break;
                case PROVINCE:
                    level_name = "省代";
                    break;
                case HEADQUARTER:
                    level_name = "总部";
                    break;
                case UNAGENT:
                    level_name = "未授权";
                    break;
            }
            currentLevel.setText(level_name);
            parentName.setText(auditDetail.getSubAuditInfo().getSubAgentParent());
            applyTime.setText(format.format(new Date(auditDetail.getApplyTime())));
            applyReason.setText(auditDetail.getApplyReason());
        }

        imgAdapter = new CommonBaseAdapter<String>(datas, R.layout.layout_img) {
            @Override
            public int getCount() {
                int count;
                count = datas.size() == 0 ? 1 : datas.size() + 1;
                return count;
            }

            @Override
            public String getItem(int position) {
                if (datas.size() != 0 && position < datas.size()) {
                    return mdatas.get(position);
                }
                return null;
            }

            @Override
            public void convert(ViewHolder holder, String s) {
                if (datas.size() != 0 && holder.getmPosition() < datas.size()) {
                    Glide.with(context).load(s).into((ImageView) holder.getView(R.id.img));
                    holder.getView(R.id.img).setOnClickListener(v -> imageBrower(holder.getmPosition(), (ArrayList<String>) datas));
                    holder.getView(R.id.del).setVisibility(View.VISIBLE);
                    holder.getView(R.id.del).setOnClickListener(v -> {
                        datas.remove(holder.getmPosition());
                        notifyDataSetChanged();
                    });
                } else {
                    Glide.with(context).load(R.mipmap.add_pic).into((ImageView) holder.getView(R.id.img));
                    holder.getView(R.id.img).setOnClickListener(v ->
                            new RxPermissions(AuditAddActivity.this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                                    .subscribe(result-> {
                                        if (result){
                                            PictureSelector.create(AuditAddActivity.this)
                                                    .openGallery(PictureMimeType.ofImage())
                                                    .selectionMode(PictureConfig.SINGLE)
                                                    .previewImage(true)
                                                    .isCamera(true)
                                                    .enableCrop(true)
                                                    .freeStyleCropEnabled(true)
                                                    .forResult(IMAGE);
                                        }
                                    }));
                    holder.getView(R.id.del).setVisibility(View.GONE);
                }
            }
        };
        payImgView.setAdapter(imgAdapter);
    }

    protected void imageBrower(int position, ArrayList<String> urls2) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        startActivity(intent);
    }

    @Override
    public void addAudit() {
        loading.setVisibility(View.VISIBLE);
        condition.setAgentId(SharePreferenceManager.getInstance().getAgentId());
        condition.setApplyLevel(level.getId());
        condition.setApplyReason(applyReason.getText().toString());
        condition.setApplyPayImg(GsonManager.getInstance().getGson().toJson(datas));
        presenter.addAudit(condition);
    }

    @Override
    public void addResult(Object result) {
        loading.setVisibility(View.GONE);
        LZToast.getInstance(context).showToast("提交成功");
        finish();
    }

    @OnClick({R.id.submit_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.submit_btn:
                if (!check()) {
                    return;
                }
                if (auditDetail == null) {
                    addAudit();
                } else {
                    passAudit();
                }
                break;
        }
    }

    private boolean check() {
        if (TextUtils.isEmpty(applyReason.getText())) {
            LZToast.getInstance(context).showToast("申请理由不能为空");
            return false;
        }if (level.getId()!=1&&level.getId()!=2) {
            if (datas.size() == 0) {
                LZToast.getInstance(context).showToast("至少上传一张截图");
                return false;
            }
        }
        return true;
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        loading.setVisibility(View.GONE);
    }

    @Override
    public void uploadForTarget(String tag, File file) {
        uploadPresenter.uploadForTarget(tag, file, progress);
        progress.setVisibility(View.VISIBLE);
        progressLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void uploadResult(String tag, String url) {
        switch (tag) {
            case "img":
                if (datas.size() != 0) {
                    datas.clear();
                    datas.add(url);
                } else {
                    datas.add(url);
                }
                imgAdapter.notifyDataSetChanged();
                break;
        }
        progress.setVisibility(View.GONE);
        progressLayout.setVisibility(View.GONE);
    }

    @Override
    public void passAudit() {
        loading.setVisibility(View.VISIBLE);
        agentPresenter.passAudit(SharePreferenceManager.getInstance().getAgentId(), id, GsonManager.getInstance().getGson().toJson(datas), applyReason.getText().toString());
    }

    @Override
    public void rejectAudit() {

    }

    @Override
    public void passResult(Object result) {
        loading.setVisibility(View.GONE);
        LZToast.getInstance(context).showToast("提交成功");
        Intent intent = getIntent();
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void rejectResult(Object result) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    uploadForTarget("img", new File(selectList.get(0).getCutPath()));
                    break;
            }
        }
    }
}
